<?php
/**
 * API helper function is here
 *
 *
 */
 namespace OM\Lib;
 use OM\OMadapter;

 class Apihelper
 {

 	public static  function CDR( $url, $data ){
 		$res = self::curl_content( $url, 50, $data );
 		if( $res )
 			return json_decode( $res,true);
 		else
 			return false;
 	}

 	public static function phone( $_phone ){
		if( $_phone && strlen( $_phone) == 12 && substr($_phone,0,2) == '01' )
			substr($_phone,1);
		return $_phone;
	}

 	/**
 	 * 根据电话号码信息获取归属地
 	 *
 	 * @param  string $phone 要查询电话号码
 	 * @return string        归属地信息
 	 */
 	public static function getPhoneAddr( $phone, $dbinfo = null  )
 	{
 		if( !$phone || strlen($phone)<7 || !$dbinfo  ){
 			return '';
 		}
 		$addr = '';
 		$phone = self::phone( $phone );
 		//连接数据查询
 		$link = mysqli_connect( $dbinfo['host'], $dbinfo['user'], $dbinfo['psw'], $dbinfo['db'], $dbinfo['port']);

		if ($link) {
		   @mysqli_query($link, "set names utf8");

		   if( ($result = mysqli_query($link, "SELECT province,area,mobilecard from om_mobilecode where codefield='".substr($phone,0,7)."'") ) ){
		   		$row = mysqli_fetch_row( $result);
		   		if( $row )
		   			$addr = $row[0].' '.$row[1];
		   	 	mysqli_free_result($result);
		   }
		   mysqli_close($link);
		}
		else{
			OMadapter::log( OMadapter::LOG_ERR.' connect database'.json_encode( $dbinfo).' Error:'.mysqli_connect_error()." \t");
		}

		return $addr;
 	}

	/**
	 * OM控制接口讲操作转换为xml
	 *
	 * @param  string   $attr     OM api control属性
	 * @param  stdClass $_attr1   参数一
	 * @param  stdClass $_attr2   参数二
	 * @return string/false       OM api接口控制信令
	 */
 	public static function _query( $attr = 'Query', $_attr1, $_attr2 = null , $api_type = "Control"  )
 	{
 		$strXml = '<?xml version="1.0" encoding="utf-8" ?>';
 		if(!$attr || !$_attr1 )
 			return false;
 		$strXml .= '<'.$api_type.' attribute="'.$attr.'">';
 		$strXml .= self::_stdVal2xml( $_attr1 );
 		if( $_attr2 )
 			$strXml .= self::_stdVal2xml( $_attr2 );
 		$strXml .= '</'.$api_type.'>';
 		return $strXml;
 	}

 	//将stdClass对象参数属性转换成 xml 字符和属性
	public static function _stdVal2xml( $stdObj )
	{
		if( !$stdObj || !( $stdObj  instanceof \stdClass ) )
			return '';
		$outXml = ' ';
		$CVals = get_object_vars( $stdObj );
		foreach($CVals as $kc => $vc )
		{
			$outXml .='<'.$kc;
			if( $vc && is_array( $vc ))
			{
				foreach($vc as $kattr=>$vattr)
				{
					if( !$vattr && $vattr!=0)
					$outXml .= " $kattr ";
					else
					{
						$outXml.=" $kattr=\"$vattr\" ";
					}
				}
			}
			$outXml .= '/>';
		}
		return $outXml;
	}

   public static function parseXML( $data )
	{
		if( !$data || !is_string( $data ) )
			return false;
		$xml = simplexml_load_string( $data );
		return  $xml ? $xml : false;
	}

    public  static function arrToXml( $arr /*要转换的数组*/, $charset='utf-8')
	{
		$strXml = '<?xml version="1.0" encoding="'.$charset.'" ?>';
		return $strXml.self::_array2xml( $arr );
	}

    public static function  _array2xml($array)
    {
        $xml='';
        foreach($array as $key=>$val){
            if(is_numeric($key)){
                $key="item id=\"$key\"";
            }else{
                //去掉空格，只取空格之前文字为key
                list($key,)=explode(' ',$key);
            }
            $xml.="<$key>";
            $xml.=is_array($val)?self::_array2xml($val):$val;
            //去掉空格，只取空格之前文字为key
            list($key,)=explode(' ',$key);
            $xml.="</$key>";
        }
        return $xml;
    }

	public static function curl_content($url, $timeout = 20, $data = false, $referer = "http://www.baidu.com")
	{
		if(function_exists('curl_init'))
		{
			$ch = curl_init();
			curl_setopt ($ch, CURLOPT_URL, $url);
			curl_setopt ($ch, CURLOPT_HEADER, 0);
			curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
			//curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
			curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
			if( $data !== false && $data )
			{
				curl_setopt ( $ch, CURLOPT_POST, 1 );
				if( $data && is_array( $data ))
					$data = http_build_query( $data );
				curl_setopt ( $ch, CURLOPT_POSTFIELDS, $data );
			}
			/*curl_setopt($ch,CURLOPT_USERAGENT,"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)");
			curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT,$timeout);
			if($referer){
				curl_setopt ($ch, CURLOPT_REFERER, $referer);
			}
			if(defined('CURLOPT_IPRESOLVE') && defined('CURL_IPRESOLVE_V4')){
				curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
			}*/
			$content = curl_exec($ch);
	        curl_close($ch);
			if($content){
				return $content;
			}
		}
		return false;
	}

 }

?>